<template>
  <div class="app-container" style="display: flex;flex-direction: column;">
    <div style="display: flex;">
      <div style="flex: 1;display: flex;flex-direction: column;">
        <div style="display: flex;gap: 10px;">
          <el-form :model="leftParams" ref="leftFormRef" label-width="100px" @submit.prevent>
            <el-form-item label="入库 Port 口" prop="port" label-position="left">
              <el-select
                v-model="leftParams.port"
                placeholder="请选择 Port 口"
                :disabled="selectFlag"
                style="width: 250px;"
                @change="changePort"
              >
                <el-option
                  v-for="item in portList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div>
            <el-button type="warning" plain :disabled="!leftParams.port" @click="missionCancel">
              Port 口任务取消
            </el-button>
          </div>
        </div>
        <div>
          <el-form :model="leftParamsTwo" ref="leftTwoFormRef" label-width="100px" @submit.prevent>
            <el-form-item label="料箱编号" prop="boxCode" label-position="left">
              <el-input
                ref="focusLeftOne"
                v-model.trim="leftParamsTwo.boxCode"
                placeholder="请扫描料箱编号"
                clearable
                style="width: 250px"
                :disabled="scanFlag"
                @keyup.enter="checkBox"
                @blur="checkBox"
              />
            </el-form-item>
            <el-form-item label="Reel ID" prop="reelId" label-position="left">
              <el-input
                ref="focusLeftTwo"
                v-model.trim="leftParamsTwo.reelId"
                placeholder="请扫描 Reel ID"
                clearable
                style="width: 250px"
                :disabled="scanFlag"
                @keyup.enter="bind"
                @blur="bind"
              />
            </el-form-item>
          </el-form>
          <el-button type="primary" style="width: 350px;" :loading="btn.bind" :disabled="scanFlag" plain @click="bind">物料绑定</el-button>
        </div>
      </div>
      <div style="flex: 1;display: flex;flex-direction: column;gap: 20px;">
        <div>
          <!-- <el-button plain type="success">搬运任务触发</el-button> -->
          <el-button plain type="success" @click="goToMaterialContainer">物料载具维护</el-button>
          <el-button plain type="danger" :disabled="!leftParams.port" @click="errorReport">Port 口异常上报</el-button>
        </div>
        <el-form :model="rightParams" ref="rightFormRef" label-width="120px">
          <el-form-item label="Reel ID" prop="reelId" label-position="left">
            <el-input
              ref="focusRight"
              v-model.trim="rightParams.reelId"
              placeholder="请扫描 Reel ID"
              style="width: 250px"
              :readonly="!scanFlag"
              @keyup.enter="extraInfo(rightParams.reelId)"
              @blur="extraInfo(rightParams.reelId)"
            />
            <el-button type="warning" plain style="margin-left: 10px;" :disabled="scanFlag" @click="clearFlag">清除</el-button>
          </el-form-item>
          <el-form-item label="料箱类型" prop="boxType" label-position="left">
            <el-input
              v-model="rightParams.boxType"
              placeholder="扫描 Reel ID后显示"
              clearable
              style="width: 250px"
              readonly
            />
          </el-form-item>
          <el-form-item label="目标厂区" prop="plantCode" label-position="left">
            <el-input
              v-model="rightParams.plantCode"
              placeholder="扫描 Reel ID后显示"
              clearable
              style="width: 250px"
              readonly
            />
          </el-form-item>
          <el-form-item label="入库任务单号" prop="orderCode" label-position="left">
            <el-input
              v-model="rightParams.orderCode"
              placeholder="扫描 Reel ID后显示"
              clearable
              style="width: 250px"
              readonly
            />
          </el-form-item>
          <el-form-item label="任务单号进度" prop="inboundProgress" label-position="left">
            <el-input
              v-model="rightParams.inboundProgress"
              placeholder="扫描 Reel ID后显示"
              clearable
              style="width: 250px"
              readonly
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div style="flex: 1;display: flex;flex-direction: column;gap: 10px;">
      <div style="font: 600;font-size: large;">物料绑定清单:</div>
      <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
      <el-table
        v-loading="btn.loading"
        :data="list"
        :span-method="objectSpanMethod"
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column prop="boxCode" align="center" label="料箱编号" />
        <el-table-column prop="compartmentCode" align="center" label="储格编号" />
        <el-table-column prop="inboundOrderCode" align="center" label="入库任务单号" />
        <el-table-column prop="reelId" align="center" label="Reel ID" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              width="280px"
              class="box-item"
              icon-color="red"
              placement="top"
              :title="`此操作将会将${scope.row.reelId}物料从${scope.row.boxCode}箱子中解绑, 是否继续?`"
              @confirm="unBind(scope.row, scope.$index)"
            >
              <template #reference>
                <el-button type="warning" icon="Close" :loading="btn.unBind === scope.$index">解绑</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page-sizes="[10, 30, 50, 100]"
          v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
      </template>
      </TableScrollContainer>
    </div>
    <!-- modal -->
    <el-dialog
      v-model="dialogVisible"
      title="操作提示"
      width="500"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <span style="font-size: large;">点击确认将 Port 口任务取消, 是否继续?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmCancel">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="提示"
      v-model="dialogVisible2"
      width="400px"
      :before-close="clearCache"
      :close-on-click-modal="false"
     >
      <div>
        {{ dialogMsg }}
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="btn.clearCache" @click="clearCache">取 消</el-button>
          <el-button type="primary" :loading="btn.bindSecond" @click="bind(second)">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="ban-reason">
      <el-dialog
        title="Port 口异常上报"
        v-model="reasonVisible"
        width="400px"
        :close-on-click-modal="false"
        :before-close="reasonClose"
       >
        <div style="display: flex;flex-direction: column;gap: 10px;">
          <div style="display: flex;align-items: center;">
            <span style="width: 80px;">Port 口</span>
            <el-input v-model="errorPort" readonly></el-input>
          </div>
          <el-input v-model="reason" type="textarea" placeholder="请输入异常原因"></el-input>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="reasonClose">取 消</el-button>
            <el-button type="primary" :loading="btn.error" @click="confirmReport">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="materialReturn">
import { getBoxTypeAPI,
  checkBoxAPI,
  bindAPI,
  getPortInfoAPI,
  getBoxInfoAPI,
  unBindAPI,
  clearCacheAPI,
  clearOrderCacheAPI,
  errorReportAPI } from "@/api/work/stockUp"
import { updatePortAPI } from "@/api/work/portManagement"
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'
const { proxy } = getCurrentInstance()
const route = useRoute()
const leftFormRef = ref(null)
const focusLeftOne = ref(null)
const focusLeftTwo = ref(null)
const focusRight = ref(null)
const reasonVisible = ref(false)
const reason = ref('')
const list = ref([])
const scanInfo = ref({})
const scanFlag = ref(true)
const dialogMsg = ref('')
const total = ref(0)
const errorInfo = ref('')
const errorPort = ref('')
const btn = reactive({
  bind: false,
  loading: false,
  unBind: '',
  bindSecond: false,
  clearCache: false,
  error: false
})
const selectFlag = ref(false)
const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
const data = reactive({
  queryParams: {
    orderNumber: null,
    pageNum: 1,
    pageSize: 10
  },
  form: {},
  leftParams: {
    port: ''
  },
  leftParamsTwo: {
    boxCode: '',
    reelId: ''
  },
  rightParams: {
    reelId: '',
    boxType: '',
    orderCode: '',
    inboundProgress: '',
    plantCode: '',
    materialCode: ''
  },
  rules: {
  }
})

const { queryParams, leftParams, leftParamsTwo, rightParams, form, rules } = toRefs(data)

const getErrorPort = () => {
  leftParams.value.port
  const errorIndex = portList.value.findIndex(item => {
    return item.value === leftParams.value.port
  })
  errorPort.value = portList.value[errorIndex].label
}

const reasonClose = async() => {
  reasonVisible.value = false
}

const confirmReport = async() => {
  try {
    btn.error = true
    const res = await errorReportAPI({
      portId: leftParams.value.port,
      remark: reason.value
    })
    if (res.errCode === '1') {
      reasonVisible.value = false
      proxy.$modal.msgSuccess(res.msg)
      proxy.resetForm("leftFormRef")
      selectFlag.value = false
      clearFlag()
      getPortInfo()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } finally {
    btn.error = false
  }
}

const clearCache = async() => {
  const suibmitForm = {
    boxCode: leftParamsTwo.value.boxCode,
    reelId: leftParamsTwo.value.reelId
  }
  try {
    btn.clearCache = true
    if (errorInfo.value === 'plant') {
      const res = await clearCacheAPI(suibmitForm)
      if (res.errCode === '1') {
        dialogVisible2.value = false
        proxy.$modal.msgSuccess(res.msg)
      } else {
        proxy.$modal.msgWarning(res.msg)
      }
    } else {
      const res = await clearOrderCacheAPI(suibmitForm)
        if (res.errCode === '1') {
        dialogVisible2.value = false
        proxy.$modal.msgSuccess(res.msg)
      } else {
        proxy.$modal.msgWarning(res.msg)
      }
    }
    leftParamsTwo.value.reelId = ''
    focusLeftTwo.value?.focus()
  } finally {
    btn.clearCache = false
  }
}

const getList = async() => {
  try {
    btn.loading = true
    queryParams.value.orderNumber = rightParams.value.orderCode
    const res = await getBoxInfoAPI(queryParams.value)
    list.value = res.data.page.records
    total.value = res.data.page.total
  } finally {
    btn.loading = false
  }
}

const extraInfo = async(val) => {
  if (!rightParams.value.reelId) return
  const count = Object.values(rightParams.value).filter(item => item)
  if (count.length > 1) return
  if (val.includes(';')) {
    const array = val.split(';')
    scanInfo.value = {
      reelId: array[7].slice(1)
    }
    rightParams.value.reelId = scanInfo.value.reelId
    useAPILogi()
  } else {
    useAPILogi()
  }
}

const useAPILogi = async() => {
  const res = await getBoxTypeAPI({
    scanCode: rightParams.value.reelId
  })
  if (res.errCode === '1') {
    if (!res.data.reelInfo.recommendBoxType) {
      rightParams.value.reelId = ''
      return proxy.$modal.msgWarning(`物料${res.data.reelInfo.materialCode}未配置标准箱类型，请在PC端维护其标准箱类型`)
    }
    rightParams.value.boxType = res.data.reelInfo.recommendBoxType || null
    rightParams.value.plantCode = res.data.reelInfo.plantCode
    rightParams.value.orderCode = res.data.reelInfo.inboundOrderCode
    rightParams.value.materialCode = res.data.reelInfo.materialCode
    rightParams.value.inboundProgress = res.data.reelInfo.inboundProgress
    proxy.$modal.msgSuccess(res.msg)
    scanFlag.value = false
    getList()
  } else {
    proxy.resetForm("rightFormRef")
    proxy.$modal.msgWarning(res.msg)
  }
}

const clearFlag = () => {
  proxy.resetForm("rightFormRef")
  proxy.resetForm("leftTwoFormRef")
  // 手动清除
  rightParams.value.materialCode = ''
  scanFlag.value = true
  list.value = []
}

const checkBox = async() => {
  const res = await checkBoxAPI({
    boxCode: leftParamsTwo.value.boxCode,
    plantCode: rightParams.value.plantCode,
    materialCode: rightParams.value.materialCode
  })
  if (res.errCode === '1') {
    // proxy.$modal.msgSuccess(res.msg)
  } else {
    leftParamsTwo.value.boxCode = ''
    proxy.$modal.msgWarning(res.msg)
  }
}

const bind = async(val) => {
  try {
    btn.bind = true
    btn.bindSecond = true
    const res = await bindAPI({
      boxCode: leftParamsTwo.value.boxCode,
      scanCode: leftParamsTwo.value.reelId,
      portId: leftParams.value.port
    })
    if (res.errCode === '1') {
      dialogVisible2.value = false
      leftParamsTwo.value.reelId = ''
      // 右边更新
      // TODO:物料用完的情况
      rightParams.value.reelId = res.data.bindInfo.reelId
      rightParams.value.boxType = res.data.bindInfo.recommendBoxType || null
      rightParams.value.plantCode = res.data.bindInfo.plantCode || null
      rightParams.value.orderCode = res.data.bindInfo.inboundOrderCode || null
      rightParams.value.materialCode = res.data.bindInfo.materialCode || null
      rightParams.value.inboundProgress = res.data.bindInfo.inboundProgress || null
      proxy.$modal.msgSuccess(res.msg)
      getList()
    } else {
      if (res.data?.plantMixInfo || res.data?.orderMixInfo) {
        dialogVisible2.value = true
        errorInfo.value = res.data?.plantMixInfo ? 'plant' : 'order'
        dialogMsg.value = res.msg
      } else {
        proxy.$modal.msgWarning(res.msg)
      }
    }
  } finally {
    btn.bindSecond = false
    btn.bind = false
  }
}

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (column.property === 'boxCode') {
    if (rowIndex > 0 && row.boxCode === list.value[rowIndex - 1].boxCode) {
      return {
        rowspan: 0,
        colspan: 1
      }
    }
    let rowspan = 1
    for (let i = rowIndex + 1; i < list.value.length; i++) {
      if (list.value[i].boxCode === row.boxCode) {
        rowspan++
      } else {
        break
      }
    }
    return {
      rowspan: rowspan,
      colspan: 1
    }
  }
  return {
    rowspan: 1,
    colspan: 1
  }
}

const changePort = async() => {
  const submitForm = {
    portId: leftParams.value.port,
    status: '1'
  }
  const res = await updatePortAPI(submitForm)
  if (res.errCode === '1') {
    selectFlag.value = true
  } else {
    leftParams.value.port = ''
    proxy.$modal.msgError(res.msg)
  }
}

const missionCancel = () => {
  dialogVisible.value = true
}

const goToMaterialContainer = () => {
  proxy.$router.push('/basicData/materialContainer')
}

const errorReport = () => {
  // 异常上报
  getErrorPort()
  reasonVisible.value = true
}

const unBind = async(row, index) => {
  console.log(row)
  const submitForm = {
    containerId: row.boxCode,
    reelId: row.reelId,
    orderNumber: rightParams.value.orderCode
  }
  try {
    btn.unBind = index
    const res = await unBindAPI(submitForm)
    if (res.errCode === '1') {
      const res = await getBoxTypeAPI({
        scanCode: rightParams.value.reelId
      })
      proxy.$modal.msgSuccess(res.msg)
      if (res.errCode === '1') {
        rightParams.value.boxType = res.data.reelInfo.recommendBoxType || null
        rightParams.value.plantCode = res.data.reelInfo.plantCode
        rightParams.value.orderCode = res.data.reelInfo.inboundOrderCode
        rightParams.value.materialCode = res.data.reelInfo.materialCode
        rightParams.value.inboundProgress = res.data.reelInfo.inboundProgress
        scanFlag.value = false
        getList()
      }
    } else {
      proxy.$modal.msgSuccess(res.msg)
    }
  } finally {
    btn.unBind = ''
  }
}

const portList = ref([])
const getPortInfo = async() => {
  const res = await getPortInfoAPI()
  portList.value = res.data.portList
    .filter(val => val.type === '1')
    .map(item => {
      return {
        value: item.portId,
        label: item.portName
      }
    })
}
getPortInfo()

const handleClose = () => {
  dialogVisible.value = false
}

const confirmCancel = async() => {
  const submitForm = {
    portId: leftParams.value.port,
    status: '0'
  }
  const res = await updatePortAPI(submitForm)
  if (res.errCode === '1') {
    dialogVisible.value = false
    selectFlag.value = false
    leftParams.value.port = ''
    getPortInfo()
  } else {
    leftParams.value.port = ''
    proxy.$modal.msgError(res.msg)
    dialogVisible.value = false
  }
}

onMounted(() => {
  focusRight.value?.focus()
})

onUnmounted(() => {
  confirmCancel()
})
</script>

<style lang="scss" scoped>
.popconfirm-base-box .box-item {
  width: 200px;
  margin-top: 10px;
}

::v-deep .el-dialog {
  transform: none;
  left: 0;
  position: relative;
  margin: 300px auto !important;
}
</style>